package com.adingxiong.pm.util;


import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * 文件上传工具类
 */
public class UploadUtils {


    /***
     *
     * @param file 上传的文件
     * @param path  文件的虚拟路径  例如/upload
     * @param fileLocation  文件的物理路径  F:/upload
     * @return 文件的虚拟路径+文件名
     */
    public static String upload(MultipartFile file, String path, String fileLocation) {
        String fileLastName = null;

        try {
            //如果目录不存在，则创建路径
            File uploadFile = new File(fileLocation);
            if (!uploadFile.exists()) {
                uploadFile.mkdir();
            }
            //获取源文件名称
            String fileName = file.getOriginalFilename();
            fileLastName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf(".", fileName.length()));
            //上传文件到指定的目录
            File uploads = new File(uploadFile, uploadFile.separator + fileLastName);
            file.transferTo(uploads);

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return path + "/" + fileLastName;
    }
}
